<template>
  <div class="beijin">
    <div id="userRegisterPage">
      <h2 class="title" style="color: black">消防器材管理系统 - 用户注册</h2>
      <div class="desc">消防器材管理系统</div>
      <a-form
        :model="formState"
        name="basic"
        autocomplete="off"
        @finish="handleSubmit"
        :labelCol="{ span: 8 }"
        :wrapperCol="{ span: 16 }"
      >
        <a-form-item
          name="userName"
          label="账号"
          :rules="[{ required: true, message: '请输入账号!' }]"
        >
          <a-input v-model:value="formState.userName" placeholder="请输入账号" />
        </a-form-item>

        <a-form-item
          name="password"
          label="密码"
          :rules="[
          { required: true, message: '请输入密码!' },
          { min: 8, message: '密码长度不能小于8位' },
        ]"
        >
          <a-input-password v-model:value="formState.password" placeholder="请输入密码" />
        </a-form-item>

        <a-form-item
          name="checkPassword"
          label="确认密码"
          :rules="[
          { required: true, message: '请输入确认密码!' },
          { min: 8, message: '确认密码长度不能小于8位' },
        ]"
        >
          <a-input-password v-model:value="formState.checkPassword" placeholder="请输入密码" />
        </a-form-item>

        <a-form-item
          name="email"
          label="邮箱"
          :rules="[{ required: true, message: '请输入邮箱!' }]"
        >
          <a-space>
            <a-input-search
              v-model:value="formState.email"
              placeholder="请输入邮箱"
              size="midium"
              @search="sendEmailCode"
            >
              <template #enterButton>
                  <a-button class="email-button" type="primary" solt="enterButton" :disabled="isDisplay">{{countDown > 0 ? countDown : '发送验证码'}}</a-button>

              </template>
            </a-input-search>

          </a-space>
        </a-form-item>

        <a-form-item
          name="emailCode"
          label="验证码"
          :rules="[
          { required: true, message: '请输入验证码!' },
          { min: 6, max: 6, message: '验证码长度为6位' },
        ]"
        >
          <a-input v-model:value="formState.emailCode" placeholder="请输入验证码" />
        </a-form-item>

        <a-form-item
          name="phone"
          label="手机号"
          :rules="[
          { required: true, message: '请输入手机号!' },
          { min: 11, max: 11, message: '手机号长度为11位' },
        ]"
        >
          <a-input v-model:value="formState.phone" placeholder="请输入手机号" />
        </a-form-item>

        <div class="tips">
          没有账号？
          <RouterLink to="/user/login">已有账号，去登录</RouterLink>
        </div>

        <a-form-item :wrapperCol="{ offset: 8, span: 16 }">
          <a-button type="primary" html-type="submit" style="width: 100%">注册</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, onUnmounted, reactive, ref } from 'vue'
import { registerUsingPost, sendEmailUsingPost } from '@/api/authUserController.ts'
import { message } from 'ant-design-vue'
import router from '@/router'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'


const formState = reactive<API.AuthUserRegisterDTO>({
  userName: '',
  password: '',
  checkPassword: '',
  email: '',
  emailCode: '',
  phone: ''
})

const isDisplay = computed(() => {
  return countDown.value > 0;
})

const countDown = ref(0)
const loginUserStore = useLoginUserStore()

const startCountDown = (seconds: number) =>{
  countDown.value = seconds
  setTimeout(() => {
    if (countDown.value <= 0) {
      return
    }
    startCountDown(countDown.value)
    countDown.value--
  },1000)
}
onMounted(() => {
  //countDown.value = loginUserStore.countDown
  window.addEventListener("beforeunload", () => setItem)
  window.addEventListener("unload", () => setItem)
  countDown.value = JSON.parse(sessionStorage.getItem("countDown") || '0')

  if(countDown.value > 0){
    startCountDown(countDown.value)
  }
})

const setItem = () => {
  console.log('页面销毁 countDown',countDown.value)
  sessionStorage.setItem("countDown", JSON.stringify(countDown.value))
}
onUnmounted(()=>{

  window.removeEventListener("beforeunload", () => setItem)
  window.removeEventListener("unload", () => setItem)
    console.log('页面销毁 countDown',countDown.value)
  //loginUserStore.setCountDown(countDown.value)
})



const sendEmailCode = async () => {
  if (!formState.email) {
    message.error('请输入邮箱')
    return
  }
  try {
    const res = await sendEmailUsingPost({
      code: '1',
      email: formState.email
    })
    if (res.data.code === 0 && res.data.data) {
      startCountDown(60)
      message.success('验证码发送成功')
    } else {
      message.error('验证码发送失败,' + res.data.message)
    }
  } catch (e) {
    message.error('验证码发送失败,' + e.message)
  }
}
/**
 * 表单提交
 * @param values
 */
const handleSubmit = async (values: any) => {
  try {
    //两次输入密码是否一致
    if (values.password !== values.checkPassword) {
      message.error('两次输入密码不一致')
      return
    }
    const res = await registerUsingPost(values)
    //注册成功，跳转登录页面
    if (res.data.code === 0 && res.data.data) {
      message.success('注册成功')
      router.push({
        path: '/user/login',
        replace: true
      })
    } else {
      message.error('注册失败,' + res.data.message)
    }
  } catch (e: any) {
    message.error('注册失败,' + e.message)
  }
}
</script>

<style scoped>
#userRegisterPage {
  max-width: 430px;
  margin: 0 auto;
}

.title {
  text-align: center;
  margin-bottom: 16px;
}

.desc {
  text-align: center;
  color: #bbb;
  margin-bottom: 16px;
}

.tips {
  text-align: right;
  margin-bottom: 16px;
  font-size: 13px;
  color: #bbb;
}
.ant-email :deep(.ant-input-search-button){
  width: 100px;

}

.email-button {
  width: 100px;
}





</style>
